package com.ktjy.order.controller;

import java.net.URLEncoder;
import java.sql.Array;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.poi.excel.ExcelWriter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ktjy.common.annotation.Log;
import com.ktjy.common.core.controller.BaseController;
import com.ktjy.common.core.domain.AjaxResult;
import com.ktjy.common.enums.BusinessType;
import com.ktjy.order.domain.Order;
import com.ktjy.order.service.IOrderService;
import com.ktjy.common.utils.poi.ExcelUtil;
import com.ktjy.common.core.page.TableDataInfo;

/**
 * 订单信息Controller
 *
 * @author ktjy
 * @date 2025-03-17
 */
@RestController
@RequestMapping("/order/order")
public class OrderController extends BaseController
{
    @Autowired
    private IOrderService orderService;

    /**
     * 树状表
     */
    @PreAuthorize("@ss.hasPermi('order:order:chars2')")
    @GetMapping("/chars2")
    public AjaxResult chars2() {
        System.out.println("报表获取动态数据。。。。。");
        Map<String, Object> map = new HashMap<>();  //临时数据库

        List<Order> list = orderService.selectOrderList(null);
        List<String> x = new ArrayList<String>();
        List y = new ArrayList<>();
        for (Order order : list) {
            x.add(order.getUserName());
            y.add(order.getOrderPrice());
        }
        System.out.println(x);
        System.out.println(y);

        map.put("x", x);
        map.put("y", y);

//        System.out.println(map);

        return AjaxResult.success(map);
    }

    /**
     * 查询订单信息列表
     */
    @PreAuthorize("@ss.hasPermi('order:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(Order order)
    {
        startPage();
        List<Order> list = orderService.selectOrderList(order);
        return getDataTable(list);
    }


//    @PreAuthorize("@ss.hasPermi('order:order:detailList')")
    @GetMapping(value = "/detail/{id}")
    public TableDataInfo detailList(@PathVariable("id") Long id)
    {
        List<Order> list = orderService.selectOrderDetailListId(id);
        System.out.println(list);
        return getDataTable(list);
    }


//    @PreAuthorize("@ss.hasPermi('order:order:userList')")
    @GetMapping("/userList")
    public TableDataInfo userList(Order order)
    {
        List<Order> list = orderService.selectUserName();
        return getDataTable(list);
    }

    /**
     * 导出订单信息列表
     */
    @PreAuthorize("@ss.hasPermi('order:order:export')")
    @Log(title = "订单信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Order order)
    {
        List<Order> list = orderService.selectOrderList(order);

        // 添加序号列
        List<Map<String, Object>> exportList = new ArrayList<>();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < list.size(); i++) {
            Order orderList = list.get(i);
            Map<String, Object> exportData = new LinkedHashMap<>();
            exportData.put("index", i + 1); // 序号列的值自增，从1开始
            exportData.put("id", orderList.getId());
            exportData.put("orderSn",orderList.getOrderSn());
            exportData.put("userName",orderList.getUserName());

            String[] gender = {"待付款","待发货","待收货","待评价","已完成","已取消"};

            for (int j = 0; j < gender.length; j++) {
                if (orderList.getOrderState()==j){
                    exportData.put("orderState",gender[j]);
                }
            }

            exportData.put("fullLocation",orderList.getFullLocation());
            exportData.put("consignee",orderList.getConsignee());
            exportData.put("telNumber",orderList.getTelNumber());
            exportData.put("actualPrice",orderList.getActualPrice());
            exportData.put("createTime",dateFormat.format(orderList.getCreateTime()));
            exportData.put("remark",orderList.getRemark());

            // 把exportData这个键值对集合添加到上面定义的exportList集合中
            // 注意看上面定义时是（List<Map<String, Object>>）
            exportList.add(exportData);
        }

        // 在内存操作，写出到浏览器
        ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter(true);
        writer.setOnlyAlias(true); // 设置成只导出有别名的字段
        // 自定义标题别名
//        writer.addHeaderAlias("index", "索引");
        writer.addHeaderAlias("id", "编号");
        writer.addHeaderAlias("orderSn", "订单流水号");
        writer.addHeaderAlias("userName", "会员名");
        writer.addHeaderAlias("orderState", "订单状态");
        writer.addHeaderAlias("fullLocation", "收货地址");
        writer.addHeaderAlias("consignee", "收货人");
        writer.addHeaderAlias("telNumber", "联系电话");
        writer.addHeaderAlias("actualPrice", "实付金额");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("remark", "备注");

        writer.write(exportList, true);

        // 自动调整列宽
        writer.autoSizeColumnAll();

        // 设置最小列宽
        int minColumnWidth = 20; // 可以根据需要调整最小列宽
        int columnCount = writer.getSheet().getRow(0).getLastCellNum();
        for (int i = 0; i < columnCount; i++) {
            int width = writer.getSheet().getColumnWidth(i);
            if (width < minColumnWidth * 256) {
                writer.getSheet().setColumnWidth(i, minColumnWidth * 256);
            }
        }



        try {
            // 设置浏览器响应的格式
            String fileName = URLEncoder.encode("订单信息", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
            out.close();
            writer.close();
        }catch (Exception e){
            System.out.println(e);
        }

    }

    /**
     * 获取订单信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('order:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(orderService.selectOrderListId(id));
    }

    /**
     * 新增订单信息
     */
    @PreAuthorize("@ss.hasPermi('order:order:add')")
    @Log(title = "订单信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Order order)
    {
        return toAjax(orderService.save(order));
    }

    /**
     * 修改订单信息
     */
    @PreAuthorize("@ss.hasPermi('order:order:edit')")
    @Log(title = "订单信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Order order)
    {
        return toAjax(orderService.updateById(order));
    }

    /**
     * 删除订单信息
     */
    @PreAuthorize("@ss.hasPermi('order:order:remove')")
    @Log(title = "订单信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Integer> ids)
    {
        return toAjax(orderService.removeByIds(ids));
    }
}